import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        // 1. 创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("root");
        // 2. 和数据库服务器建立连接
        Connection connection = dataSource.getConnection();
        // 3. 构造SQL语句
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);   // 提前预编译下
        // 4. 执行SQL语句
        ResultSet resultSet = statement.executeQuery();
        // 5. 遍历结果集
        while (resultSet.next()){
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");
            System.out.println("name = " + name + " age = " + age);
        }
        // 5.释放必要的资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
